package com.ibeeking.found.uaa.cp.config.auth.grant;

import com.ibeeking.found.uaa.cp.config.auth.token.AbstractCustomTokenGranter;
import com.ibeeking.found.uaa.cp.model.CpAuthModel;
import com.ibeeking.found.uaa.cp.model.CpUserDetails;
import com.ibeeking.found.uaa.cp.service.ICpUserDetailsService;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.OAuth2RequestFactory;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import java.util.Map;

/**
 * @Author ibeeking
 */
public class WxCpTokenGranter extends AbstractCustomTokenGranter {

    private static final String GRANT_TYPE = "wx_cp";
    private static final String OPEN_ID = "open_id";

    private final ICpUserDetailsService userDetailsServiceImpl;

    public WxCpTokenGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsServiceImpl, OAuth2RequestFactory requestFactory, ICpUserDetailsService userDetailsServiceImpl) {
        super(tokenServices, clientDetailsServiceImpl, requestFactory, GRANT_TYPE);
        this.userDetailsServiceImpl = userDetailsServiceImpl;
    }

    @Override
    protected CpUserDetails getUserDetails(Map<String, String> parameters) {
        CpAuthModel cpAuthModel = new CpAuthModel();
        cpAuthModel.setOpenId(parameters.get(OPEN_ID));
        CpUserDetails userDetails = userDetailsServiceImpl.cpAuthLogin(cpAuthModel);
        return userDetails;
    }
}
